package com.agh.portal.web;

import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.agh.portal.domain.Ad;
import com.agh.portal.domain.MainPagePost;
import com.agh.portal.domain.enumeration.PostCategory;
import com.agh.portal.service.DataService;
import com.agh.portal.service.SecurityUtils;

@RequestMapping("/mainpageposts")
@Controller
@RooWebScaffold(path = "mainpageposts", formBackingObject = MainPagePost.class)
@RooWebFinder
public class MainPagePostController {
	
	@Autowired
	SecurityUtils secUtils;
	
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid MainPagePost mainPagePost, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, mainPagePost);
            return "mainpageposts/create";
        }
        uiModel.asMap().clear();
        mainPagePost.setCreationDate(new Date());
        mainPagePost.persist();
        return "redirect:/mainpageposts/" + encodeUrlPathSegment(mainPagePost.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        MainPagePost mainPagePost = MainPagePost.findMainPagePost(id);
        uiModel.addAttribute("mainpagepost", mainPagePost);
        uiModel.addAttribute("comments", DataService.sortCommentsByDate(mainPagePost.getComments()));
        uiModel.addAttribute("itemId", id);
        return "mainpageposts/show";
    }
	
    @RequestMapping(produces = "text/html")
    public String list(
    		@RequestParam(value = "page", required = false) Integer page, 
    		@RequestParam(value = "size", required = false) Integer size, 
    		@RequestParam(value = "category", required = false) String category,
    		@RequestParam(value = "sortFieldName", required = false) String sortFieldName,
    		@RequestParam(value = "sortOrder" , required = false) String sortOrder,
    		Model uiModel) {
    	if (page != null || size != null || category != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            PostCategory postCategory = PostCategory.parseEnum(category);
            sortFieldName = sortFieldName == null ? "creationDate" : sortFieldName;
            sortOrder = sortOrder == null ? "desc" : sortOrder;
           
            if(postCategory != null){
            	uiModel.addAttribute("mainpageposts", DataService.parseMainPagePostsToDataComponent(MainPagePost.findMainPagePostEntriesByCategory(postCategory, firstResult, sizeNo, sortFieldName, sortOrder).getResultList()));            	
            }else{
            	uiModel.addAttribute("mainpageposts", DataService.parseAdsToDataComponent(Ad.findAdEntries(firstResult, sizeNo, sortFieldName, sortOrder)));
            }
            
            float nrOfPages = (float) MainPagePost.countMainPagePosts() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
        	uiModel.addAttribute("mainpageposts",DataService.parseMainPagePostsToDataComponent(MainPagePost.findAllMainPagePosts()));
        }
        addDateTimeFormatPatterns(uiModel);
        return "mainpageposts/list";
    }

    void populateEditForm(Model uiModel, MainPagePost mainPagePost) {
        uiModel.addAttribute("mainPagePost", mainPagePost);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("student", secUtils.getLoggedStudent());
        uiModel.addAttribute("postcategorys", Arrays.asList(PostCategory.values()));
    }

}
